<?php
defined( 'BASEPATH' ) or exit( 'No direct script access allowed' );
class Permission_handle extends MY_Controller
{
    function get_list()
    {
        $role_id = ( int ) $this->input->get( 'role_id' );
        $this->load->model( 'user_permission_model' );
        $type = $this->input->get( 'type' );
        switch ($type)
        {
            case 'menu' :
                $permission = $this->user_permission_model->uris( $role_id, 1 );
                $this->load->model( 'menu_model' );
                $list = $this->menu_model->get_submenus();
                break;
            case 'api' :
                $permission = $this->user_permission_model->uris( $role_id, 0 );
                $this->load->model( 'api_model' );
                $list = $this->api_model->get_list();
                break;
            default :
                $this->rs->err( "参数type不匹配！" );
        }
        if ($permission !== false && $list !== false)
        {
            $uris = array ();
            foreach ( $permission as $p )
            {
                $uris[] = $p['uri'];
            }
            foreach ( $list as &$i )
            {
                $i['permission'] = in_array( $i['uri'], $uris );
            }
            $this->rs->ok( array (
                    'list' => $list,
                    'count' => count( $list ) 
            ) );
        }
        $this->rs->err();
    }
    function modify()
    {
        $role_id = ( int ) $this->input->post( 'role_id' );
        $uri = $this->input->post( 'uri' );
        if (empty( $uri ))
        {
            $this->rs->err( 2 );
        }
        $uri_type = ( int ) $this->input->post( 'uri_type' );
        $flag = $this->input->post( 'flag' ) ? 1 : 0;
        
        $this->load->model( 'user_permission_model' );
        if ($this->user_permission_model->exist( $role_id, $uri ))
        {
            $result = $this->user_permission_model->set( $role_id, $uri, $flag );
            if ($result !== false)
            {
                $this->rs->ok();
            }
        }
        else
        {
            $result = $this->user_permission_model->insert( array (
                    'role_id' => $role_id,
                    'uri' => $uri,
                    'uri_type' => $uri_type,
                    'flag' => $flag 
            ) );
            if ($result !== false)
            {
                $this->rs->ok();
            }
        }
        $this->rs->err();
    }
}